package com.ncmmall.mall.controller.business.order;

import com.feijin.commons.excel.ExcelExports;
import com.feijin.commons.lang.Dates;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.order.Order;
import com.ncmmall.domain.business.order.OrderDetail;
import com.ncmmall.domain.business.order.QOrder;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author linxs
 * @Description: 采购管理
 * @Date: 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/merchant/purchase/order")
public class MerchantPurchaseOrderController {

    private final static Logger logger = LoggerFactory.getLogger(MerchantPurchaseOrderController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, Order order) throws ParseException {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());
        String hql = builderSQL("select u from Order u where u.member.id = :id and u.isSupplier = 1 ", params, order);
        QueryPage<Order> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Order.class);

        page.setResult(Lists.transform(page.getResult(), new Function<Order, Order>() {
            @Nullable
            @Override
            public Order apply(@Nullable Order input) {

                int deliveryCount = 0;
                int cloudCount = 0;
                for (OrderDetail detail : input.getDetails()) {
                    deliveryCount += detail.getDeliveryQuantity();
                    cloudCount += (detail.getQuantity() - detail.getDeliveryQuantity());
                }

                input.setDeliveryCount(deliveryCount);
                input.setCloudCount(cloudCount);

                return input;
            }
        }));


        model.addAttribute("page", page).addAttribute("params", order);

        return "merchant/order/purchase/list";
    }


    /**
     * 导出Excel
     */
    @RequestMapping(value = "/exports", method = RequestMethod.GET)
    private void exports(HttpServletRequest request, HttpServletResponse response, Order order) throws ParseException {
        Map params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());

        String sql = "select u from Order u where u.merchant.id = :id and u.isIssuingType = 0 ";
        String hql = builderSQL(sql, params, order);

        List<Order> result = queryChannelService.findAll(hql, params, Order.class);
        for (Order item : result) {

            List<String> names = Lists.newArrayList();
            for (OrderDetail detail : item.getDetails()) {
                names.add(detail.getGoodsName());
            }

            item.setExpressCompany(Joiner.on("、").join(names));

        }

        Map<String, Object> data = ImmutableMap.of("result", result);
        ExcelExports document = new ExcelExports.Templates().formTemplate("merchantOrders.ftl").bind(data).store("merchantOrders.xls").build();

        try {
            document.generate();
            Webs.download(request, response, document.getFile(), "订单" + Dates.transDateToStr(new Date()) + ".xls");

        } catch (Exception e) {
            logger.error("[导出异常]", e);
        }
    }

    /**
     * 查看详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    public String detail(Model model, @PathVariable("id") long id) {

        Order order = queryChannelService.findOne(QOrder.order.id.eq(id), Order.class);


        List<Goods> giftGoodses = Lists.newArrayList();

        //赠品活动订单
        if (order.getMarketingType() == 1) {
            giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", order.getGiftActivity().getId()), Goods.class);
        }

        model.addAttribute("order", order);
        model.addAttribute("giftgoodses", giftGoodses);

        return "merchant/order/purchase/detail";
    }

    /**
     * 查看详情
     */
    @RequestMapping(value = "/{orderNo}/orderDetail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("orderNo") String orderNo) {

        Order order = queryChannelService.findOne(QOrder.order.orderNo.eq(orderNo), Order.class);


        List<Goods> giftGoodses = Lists.newArrayList();

        //赠品活动订单
        if (order.getMarketingType() == 1) {
            giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", order.getGiftActivity().getId()), Goods.class);
        }

        model.addAttribute("order", order);
        model.addAttribute("giftgoodses", giftGoodses);

        return "merchant/order/detail";
    }


    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Order order) throws ParseException {

        if (order.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", order.getStatus());
        }

        if (null != order.getSupplier() && !Strings.isNullOrEmpty(order.getSupplier().getRealName())) {
            sql += " and u.supplier.realName like :suppliername ";
            params.put("suppliername", "%" + order.getSupplier().getRealName() + "%");
        }

        if (!Strings.isNullOrEmpty(order.getOrderNo())) {
            sql += " and u.orderNo like :orderno ";
            params.put("orderno", "%" + order.getOrderNo() + "%");
        }

        if (!Strings.isNullOrEmpty(order.getDeliveryMobile())) {
            sql += " and u.deliveryMobile like :deliverymobile ";
            params.put("deliverymobile", "%" + order.getDeliveryMobile() + "%");
        }

        if (!Strings.isNullOrEmpty(order.getDeliveryName())) {
            sql += " and u.deliveryName like :deliveryname ";
            params.put("deliveryname", "%" + order.getDeliveryName() + "%");
        }

        if (!Strings.isNullOrEmpty(order.getBeginTime())) {
            sql += " and u.createTime >= :btime ";
            params.put("btime", new Date(new SimpleDateFormat("yyyy-MM-dd").parse(order.getBeginTime()).getTime()));
        }

        if (!Strings.isNullOrEmpty(order.getEndTime())) {
            sql += " and u.createTime <= :etime ";
            params.put("etime", new Date(new SimpleDateFormat("yyyy-MM-dd").parse(order.getEndTime()).getTime()));
        }

        if (!Strings.isNullOrEmpty(order.getOrderByCreateTime())) {
            sql += " order by u.createTime " + order.getOrderByCreateTime();
        }

        if (!Strings.isNullOrEmpty(order.getOrderByPrice())) {
            sql += " order by u.price " + order.getOrderByPrice();
        }

        if (!sql.contains("order by")) {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }

}
